package com.sinosoft.jwjw.utils;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * Created by LB on 2018/6/6.
 */
public class ConvertUtil {



    public static String toString(Object obj) {
        if(obj != null){
            return obj.toString();
        }
        return "";
    }

    public static String toSqlString(Object obj) {
        return toString(obj).replace("'","''").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    }

    public static int toInt(Object obj) {
        return toInt(obj,0);
    }
    public static int toInt(Object obj, int defaultvalue) {
        if(obj != null){
            try{
                return Integer.parseInt(obj.toString());
            }
            catch (Exception ee)
            {
                return defaultvalue;
            }
        }
        return defaultvalue;
    }
    public static double toDouble(Object obj) {
        return toDouble(obj,0);
    }
    public static double toDouble(Object obj, double defaultvalue) {
        if(obj != null && obj instanceof Double){
            return (Double)obj;
        }
        return defaultvalue;
    }

    public static Long toLong(Object obj) {
        if(obj != null){
            try
            {
                return Long.valueOf(String.valueOf(obj));
            }
            catch (Exception e)
            {
                return Long.valueOf(0);
            }
        }
        return Long.valueOf(0);
    }





    // 短日期格式
    public static String DATE_FORMAT_Date = "yyyy-MM-dd";
    // 长日期格式
    public static String DATE_FORMAT_STANDARD = "yyyy-MM-dd HH:mm:ss";


    public static String addDateTime(Date dateTime, String format,Long second) {
        if (toString(format).equals(""))
            format = DATE_FORMAT_STANDARD;

        return toDateString(new Date(dateTime.getTime() + second * 1000L),format);
    }

    /**
     * 将长整型数字转换为日期格式的字符串
     * @param time
     * @param format
     * @return
     */
    public static String toDateString(long time, String format) {
        if (time > 0l) {
            if (toString(format).equals(""))
                format = DATE_FORMAT_STANDARD;
            SimpleDateFormat sf=new SimpleDateFormat(format);
            Date date = new Date(time);
            return sf.format(date);
        }
        return "";
    }
    public static String toDateString(long time) {
        return  toDateString(time,DATE_FORMAT_STANDARD);
    }
    /**
     * 将java.util.Date对象转化为String字符串
     * @param date
     *            要格式的java.util.Date对象
     * @param strFormat
     *            输出的String字符串格式的限定（如："yyyy-MM-dd HH:mm:ss"）
     * @return 表示日期的字符串
     */
    public static String toDateString(Date date, String strFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(strFormat);
        String str = sf.format(date);
        return str;
    }
    public static String toDateString(Date date) {
        return toDateString(date,DATE_FORMAT_STANDARD);
    }

    /**
     * 将java.sql.Timestamp对象转化为String字符串
     * @param time
     *            要格式的java.sql.Timestamp对象
     * @param strFormat
     *            输出的String字符串格式的限定（如："yyyy-MM-dd HH:mm:ss"）
     * @return 表示日期的字符串
     */
    public static String toDateString(java.sql.Timestamp time, String strFormat) {
        if (toString(strFormat).equals(""))
            strFormat = DATE_FORMAT_STANDARD;
        SimpleDateFormat sf=new SimpleDateFormat(strFormat);
        return sf.format(time);
    }
    public static String toDateString(java.sql.Timestamp time) {
        return  toDateString(time,DATE_FORMAT_STANDARD);
    }

    /**
     * 将String字符串转换为java.sql.Timestamp格式日期,用于数据库保存
     * @param strDate
     *            表示日期的字符串
     * @param dateFormat
     *            传入字符串的日期表示格式（如："yyyy-MM-dd HH:mm:ss"）
     * @return java.sql.Timestamp类型日期对象（如果转换失败则返回null）
     */
    public static java.sql.Timestamp toSqlDate(String strDate, String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        Date date = null;
        try {
            date = sf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Timestamp dateSQL = new java.sql.Timestamp(date.getTime());
        return dateSQL;
    }
    public static java.sql.Timestamp toSqlDate(String strDate) {
        return  toSqlDate(strDate,DATE_FORMAT_STANDARD);
    }

    /**
     * 将Long转换为java.sql.Timestamp格式日期,用于数据库保存
     * @param strDate
     *            表示日期的字符串
     * @param dateFormat
     *            传入字符串的日期表示格式（如："yyyy-MM-dd HH:mm:ss"）
     * @return java.sql.Timestamp类型日期对象（如果转换失败则返回null）
     */
    public static java.sql.Timestamp toSqlDate(Long strDate, String dateFormat) {
        String dateStr = toDateString(strDate,dateFormat);
        return toSqlDate(dateStr,dateFormat);
    }
    public static java.sql.Timestamp toSqlDate(Long strDate) {
        return toSqlDate(strDate,DATE_FORMAT_STANDARD);
    }

    public static java.sql.Timestamp toSqlDate(Date date) {
        String dateStr = toDateString(date,"yyyy-MM-dd HH:mm:ss SSS");
        return toSqlDate(dateStr,"yyyy-MM-dd HH:mm:ss SSS");
    }

    /**
     * 将日期格式的字符串转换为长整型
     * @param date
     * @param format
     * @return
     */
    public static Long toDateLong(String date, String format) {
        try {
            if (!toString(format).equals("")) {
                if (toString(format).equals(""))
                    format = DATE_FORMAT_STANDARD;
                SimpleDateFormat sf = new SimpleDateFormat(format);
                return sf.parse(date).getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }
    public static Long toDateLong(String date) {
        return  toDateLong(date,DATE_FORMAT_STANDARD);
    }




    public static JSONObject deepMerge( JSONObject... jos){
        JSONObject jo = new JSONObject();
        for ( JSONObject temp :jos){
            jo.putAll(temp);
        }
        return jo;
    }

    public static String toJSON(JSONObject json) {
        if(json == null){
            return "";
        }
        return json.toString();
    }
    public static String toJSON(JSONArray json) {
        if(json == null){
            return "[]";
        }
        return json.toString();
    }


    static ObjectMapper mapper = new ObjectMapper();
    static {
//        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
//        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
//        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
//        mapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);
//        mapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

//        mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false);
//        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
//        mapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, false);
    }
    public static <T> String toJSON(T obj) {
        if(obj == null){
            return "{}";
        }
        try {
            String result = mapper.writeValueAsString(obj).replace("\n","").replace("\r","");
            return result;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{}";

    }


    /**
     *@描述   string to JSONObject
     *@参数   String json字符串
     *@返回值  JSONObject
     */
    public static JSONObject toJSONObject(String json) {
        if(json == null || "".equals(json)){
            json="{}";
        }
        return JSONObject.fromObject(json);
    }

    public static <T> JSONObject toJSONObject(T obj) {
        return JSONObject.fromObject(toJSON(obj));
    }

    public static JSONObject toJSONObject(JSONArray json) {
        String jsonString = json.toString();
        if(jsonString.length() <= 2){
            return new JSONObject();
        }
        else{
            jsonString = jsonString.substring(1,jsonString.length()-1);
            return JSONObject.fromObject(jsonString);
        }
    }

    public static <V> JSONObject toJSONObject(Map<String,V> map) {
        return JSONObject.fromObject(map);
    }


    public static <V> Map<String,V> toMap(String json) {
        return JSONObject.fromObject(json);
    }
    public static <V> Map<String,V> toMap(JSONObject json) {
        return json;
    }


    /**
     * string to JSONArray
     */
    public static JSONArray toJSONArray(String json) {
        return JSONArray.fromObject(json);
    }

    public static <T> JSONArray toJSONArray(List<T> list) {
        JSONArray ja = new JSONArray();
        if(list == null) return ja;
        for (T obj : list) {
            ja.add(toJSONObject(toJSON(obj)));
        }
        return ja;
    }

//    public static <V> List<Map<String,V>> toListMap(String json) {
//        return (List)JSONArray.fromObject(json);
//    }


    /**
     * string to 实体类T
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        return (T) JSONUtil.toBean(json,clazz);
    }
    public static <T> T toObject(JSONObject jo, Class<T> clazz) {
        return (T) toObject(jo.toString(),clazz);
    }

    /**
     * string to List<T>
     */
    public static <T> List<T> toListObject(String json, Class<T> clazz) {
        JSONArray jsonArray = JSONArray.fromObject(json);
        return (List<T>)JSONArray.toList(jsonArray, clazz);
    }


    /**
     * 用来添加id 20位无横线
     * @return
     */
    public static String getUUID20() {
        String s = UUID.randomUUID().toString();
        // 去掉“-”符号
        return (s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)
                + s.substring(19, 23) + s.substring(24)).substring(0, 20);
    }

}
